package towa.com.remoteWMP;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

import android.util.Log;

public class ComThread extends Thread {

	private Socket socket;
	private OutputStream os;
	private InputStream is;
	private byte[] data;
	
	public ComThread() {}
	
	public synchronized void sendData(SocketChannel sChannel, String data) throws IOException {
		CharsetEncoder encoder = Charset.forName("ISO-8859-1").newEncoder();
//		ByteBuffer buffer = ByteBuffer.allocate(1024);
		sChannel.write(encoder.encode(CharBuffer.wrap(data.toCharArray())));
	}
	
	public synchronized static SocketChannel createSocketChannel(String hostName, int port) throws IOException {
	    // Create a non-blocking socket channel
	    SocketChannel sChannel = SocketChannel.open();
	    sChannel.configureBlocking(true);
	    // Send a connection request to the server; this method is non-blocking
	    sChannel.socket().connect(new InetSocketAddress(hostName, port), 5000);
	    return sChannel;
	}
	
	public synchronized SocketChannel initSocket(String host, int port) throws IOException {
		SocketChannel sChannel = null;
	    // Create a non-blocking socket channel on a port
	    sChannel = ComThread.createSocketChannel(host, port);
	    Log.i("WMPRemoteConnection", "sChannel: " + sChannel.toString());
	    // Before the socket is usable, the connection must be completed
	    // by calling finishConnect(), which is non-blocking
	    int i = 0;
	    while (!sChannel.finishConnect()) {
	        Log.i("WMPRemoteConnection", "Tick: " + (i++));
	    }
	    // Socket channel is now ready to use
//		Log.i("WMPRemoteConnection", "Ready to use");
		return sChannel;
	}
	
	public synchronized String getData() {
		return data.toString();
	}
	
	public synchronized void closeAll() {
		try {
			is.close();
			os.close();
			socket.close();
		} catch (IOException e) {
			Log.e("WMPRemote", e.toString());
		}
	}
	
}
